package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.*;
import com.itheima.mapper.OrdersMapper;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {



    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;


    //黑马的实现
    @Override
    @Transactional
    public void submit(Orders orders,HttpSession session) {

        //获得用户id
        Long user = (Long) session.getAttribute("user");

        //查询当前购物车的数据
        LambdaQueryWrapper<ShoppingCart> qw=new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,user);
        List<ShoppingCart> list=shoppingCartService.list(qw);


        //抛异常  购物车为空
        if(list==null||list.size()==0){
            return;
        }

        //查询用户数据
        User user1 = userService.getById(user);


        //查询地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        //抛出异常  地址信息有误
        if (addressBook==null){
            return;
        }

        AtomicInteger amount=new AtomicInteger();

        //插入id
        Long orderId=IdWorker.getId();
        List<OrderDetail> orderDetails =new ArrayList<>();

        for (ShoppingCart item:
             list) {
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            orderDetails.add(orderDetail);
        }

        //向订单表插入数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setStatus(2);
        orders.setUserId(user);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserName(user1.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        this.save(orders);


        //向订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(qw);


    }

    //自己写的实现
    @Override
    @Transactional
    public void sub(Orders orders, HttpSession session) {
        Long userId= (Long) session.getAttribute("user");
        Long addressBookId = orders.getAddressBookId();

        orders.setUserId(userId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());

        //设置支付时间
        orders.setCheckoutTime(LocalDateTime.now());

        //设置实际收取的金额

        //用userid查询购物车数据
        LambdaQueryWrapper<ShoppingCart> qw=new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(qw);
        List<OrderDetail> list1=new ArrayList<>();

        //获得订单总金额
        BigDecimal totalAmount=new BigDecimal("0");
        for (ShoppingCart s:
                list) {

            OrderDetail orderDetail=new OrderDetail();
            if (s.getDishId()!=null){
                //用菜品id查询菜品
                Long dishId = s.getDishId();

                //设置菜品id
                orderDetail.setDishId(dishId);

                //查询口味信息
                String dishFlover=s.getDishFlavor();

                //设置口味信息
                orderDetail.setDishFlavor(dishFlover);

                //获取数量信息
                Integer number = s.getNumber();
                orderDetail.setNumber(number);

                //设置总钱数
                orderDetail.setAmount(BigDecimal.valueOf(number).multiply(s.getAmount()));

                totalAmount=totalAmount.add(orderDetail.getAmount());



                //设置图片
                orderDetail.setImage(dishService.getById(dishId).getImage());

                //设置名称
                orderDetail.setName(dishService.getById(dishId).getName());

                //加入订单list
                list1.add(orderDetail);
            }else if(s.getSetmealId()!=null){

                //查询何设置套餐id
                Long setId=s.getSetmealId();
                orderDetail.setSetmealId(setId);

                //查询和设置套餐数量 及价格
                Integer number=s.getNumber();
                BigDecimal decimal=s.getAmount();

                orderDetail.setNumber(number);


                //该套餐的总金额
                BigDecimal amount=decimal.multiply(BigDecimal.valueOf(number));
                orderDetail.setAmount(amount);
                totalAmount=totalAmount.add(amount);

                //设置图片
                orderDetail.setImage(setmealService.getById(setId).getImage());

                //设置名称
                orderDetail.setName(setmealService.getById(setId).getName());

                //加入list1
                list1.add(orderDetail);

            }

        }
        //创建orders对象  保存至orders表中
        orders.setAmount(totalAmount);

        this.save(orders);
        Long id=orders.getId();

        List<OrderDetail> list2=new ArrayList<>();
        for (OrderDetail or:
                list1) {
            or.setOrderId(id);
            list2.add(or);
        }

        orderDetailService.saveBatch(list2);

        //如果提交订单需要清空购物车
        shoppingCartService.remove(qw);
        //保存明细至订单明细表中
    }
}
